package com.liuyucheng.concurrent.deadlock;

public class DeadlockDemo {
    private static final Object RESOURCE_1 = new Object();
    private static final Object RESOURCE_2 = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            synchronized (RESOURCE_1) {
                System.out.println("Thread 1: 持有锁 1...");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1: 等待锁 2...");
                synchronized (RESOURCE_2) {
                    System.out.println("Thread 1: 持有锁 1 和 2...");
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (RESOURCE_2) {
                System.out.println("Thread 2: 持有锁 2...");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 2: 等待锁 1...");
                synchronized (RESOURCE_1) {
                    System.out.println("Thread 2: 持有锁 1 和 2...");
                }
            }
        });

        thread1.setName("线程001");
        thread2.setName("线程002");

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}